package com.xyb.config.exception;

import com.xyb.entity.Result;
import com.xyb.entity.StatusCode;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 全局异常处理器
 */
@ControllerAdvice
public class GlobalException {

    @ResponseBody
    @ExceptionHandler(value = Exception.class)
    public Result handler(HttpServletRequest request, HttpServletResponse response, Exception e) {
        // 出现异常也给前台返回 200,这个是 Http 的状态码
        response.setStatus(200);
        /**
         * 自定义结果集
         */
        Result result = new Result<>();
        result.setFlag(false);

        /**
         * 如果异常是业务异常,手动封装
         */
        if (e instanceof MyException) {
            MyException myException = (MyException) e;
            result.setMsg(((MyException) e).getMsg());

            int code = ((MyException) e).getCode();
            boolean flag = false; //状态码是否存在标识
            //如果code存在就用已经设置的状态码,不存在就设为 50000
            StatusCode[] codes = StatusCode.values();
            int length = codes.length;
            for (int i = 0; i < length; i++) {
                int tmpCode = codes[i].getCode();
                if (tmpCode == code) {
                    flag = true;
                    code = tmpCode;
                    break;
                }
            }
            code = flag?code:StatusCode.UNDEFINED_ERROR.getCode();
            result.setCode(code);
            return result;
        }

        /**
         * 空指针异常
         */
        if(e instanceof NullPointerException){
            result.setMsg(StatusCode.NULL_POINTER_EXCEPTION.getMsg());
            result.setCode(StatusCode.NULL_POINTER_EXCEPTION.getCode());
            return result;
        }

        /**
         * 数组越界异常
         */



        /**
         * 如果是其他异常,默认参数
         */
        result.setMsg(e.getClass().toString() + ": " + e.getLocalizedMessage());
        result.setCode(StatusCode.UNDEFINED_ERROR.getCode());
        return result;
    }
}
